import 'package:flutter/material.dart';

/// Tab分类组件
class TabCategory extends StatefulWidget {
  // 分类数据列表
  final List<Map<String, dynamic>> categories;
  // 初始选中的分类ID
  final String initialSelectedCategoryId;
  // 分类选中回调函数
  final ValueChanged<String> onCategorySelected;
  // 是否显示阴影
  final bool showShadow;

  const TabCategory({
    super.key,
    required this.categories,
    this.initialSelectedCategoryId = 'all',
    required this.onCategorySelected,
    this.showShadow = false,
  });

  @override
  State<TabCategory> createState() => _TabCategoryState();
}

class _TabCategoryState extends State<TabCategory> {
  // 当前选中的分类ID
  late String _selectedCategoryId;

  @override
  void initState() {
    super.initState();
    _selectedCategoryId = widget.initialSelectedCategoryId;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: widget.showShadow
            ? [
                BoxShadow(
                  color: Colors.grey.withValues(alpha: 0.2),
                  spreadRadius: 1,
                  blurRadius: 3,
                  offset: const Offset(0, 1),
                ),
              ]
            : null,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: widget.categories.map((category) {
          final bool isSelected = _selectedCategoryId == category['id'];
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedCategoryId = category['id'];
              });
              // 调用回调函数
              widget.onCategorySelected(category['id']);
            },
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 8,
              ),
              decoration: BoxDecoration(
                color: isSelected ? Colors.lightBlue : Colors.grey[100],
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
                category['name'],
                style: TextStyle(
                  color: isSelected ? Colors.white : Colors.black87,
                  fontWeight: isSelected
                      ? FontWeight.bold
                      : FontWeight.normal,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}
